﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using IEx;
using IEx.Common;
using IEx.Utilities;

namespace IEx.ParserBuilder.Youtube
{
    public class YoutubeRequestBuilder : DefaultRequestBuilder
    {
        private string refererUrl = "https://www.youtube.com/results";

        public YoutubeRequestBuilder()
            : base("GET", "application/x-www-form-urlencoded")
        {
        }

        public override void BeginBuildRequest(SourceItem item)
        {
            if (item.Url.IndexOf("?") == -1 && !string.IsNullOrEmpty(item.SearchCode))
            {
                string searchCode = item.SearchCode;
                searchCode = searchCode.Replace(" ", "+");
                searchCode = searchCode.Replace("--", "+");
                searchCode = searchCode.ToLower();
                string requestQuery = searchCode;
                item.Url = item.Url + "results?search_query=" + requestQuery;
            }
        }

        public override void BuildRequest(ref HttpWebRequest request)
        {
            // build request url
            if (request.RequestUri.ToString().IndexOf("?") == -1)
            {
                string queryString = string.Empty;
                foreach (string key in this.paramCollection.AllKeys)
                {
                    queryString += string.Format(
                        "{0}={1}&",
                        Uri.EscapeDataString(key),
                        Uri.EscapeDataString(this.paramCollection[key]));
                }
                queryString = queryString.TrimEnd('&');
                request = (HttpWebRequest)WebRequest.Create(request.RequestUri.ToString() + "?" + queryString);
            }

            var arrRequestPart = request.RequestUri.AbsoluteUri.Split('?');
            if (!string.IsNullOrEmpty(arrRequestPart[1]))
            {
                request.Referer = refererUrl + "?" + arrRequestPart[1];
            }
            else
            {
                Uri uriRequest = Utility.CreateNewUriForNextPage(refererUrl);
                request.Referer = uriRequest.ToString();
            }
        }
    }
}
